package com.achao.basecommon.aop;

import com.achao.basecommon.annotation.ApiMonitorAnnotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Description：接口监控-统计 实现
 * @date：2023/8/4 14:20
 */
@Aspect
@Component
public class ApiMonitorAop {
    private static final Logger logger = LoggerFactory.getLogger(ApiMonitorAop.class);

    /**
     * 拦截指定注解
     */
    @Pointcut("@annotation(com.achao.basecommon.annotation.ApiMonitorAnnotation)")
    public void monitorResponseTime() {}

    /**
     * 拦截器具体实现
     *
     * @param pjp
     */
    @Around("monitorResponseTime()")
    public Object interceptor(ProceedingJoinPoint pjp) throws Throwable {
        System.out.printf("进入切面");
        Long currentTime = System.currentTimeMillis();
        ApiMonitorAnnotation annotation = getAnnotationFromJoinPoint(pjp);
        //TODO 这里可以校验一些东西 比如token、、以后补充
        //checkAuthAndAuth(annotation);
        Object proceed = pjp.proceed();
        logger.info(String.format("接口响应统计:接口模块%s-接口编码：%s 接口名称：%s 请求服务器用时(毫秒):%s",
                annotation.apiModel(),
                annotation.apiCode(),
                annotation.apiName(),
                String.valueOf(System.currentTimeMillis() - currentTime)));
        return proceed;
    }

    /**
     * 从切点获取接口响应注解
     *
     * @param pjp
     * @return
     */
    private ApiMonitorAnnotation getAnnotationFromJoinPoint(ProceedingJoinPoint pjp) {
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        return method.getAnnotation(ApiMonitorAnnotation.class);
    }
}
